package com.metersbonwe.seq;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 序列号队列
 * 
 * @author tonyruiyu
 *
 */
public final class SequenceQueue {

    private String                   queueName;

    private int                      queueCapacity = 2000;

    private int                      inc           = 1;

    private ArrayBlockingQueue<Long> queue;

    public SequenceQueue(String queueName, int queueCapacity) {
        this(queueName, queueCapacity, 1);
    }

    public SequenceQueue(String queueName, int queueCapacity, int inc) {
        super();
        this.queueName = queueName;
        this.queueCapacity = queueCapacity;
        this.inc = inc;
        this.queue = new ArrayBlockingQueue<Long>(queueCapacity);
    }

    public String getQueueName() {
        return queueName;
    }

    public int getQueueCapacity() {
        return queueCapacity;
    }

    public ArrayBlockingQueue<Long> getQueue() {
        return queue;
    }

    public void add(Long lastSeq, int count) throws InterruptedException {
        while (count > 0) {
            queue.put(lastSeq);
            lastSeq -= inc;
            count--;
        }
    }

    public void add(Long seq) {
        queue.add(seq);
    }

    public long poll() {
        return queue.poll();
    }

    public Long poll(long timeout, TimeUnit unit) throws InterruptedException {
        return queue.poll(timeout, unit);
    }

    public int size() {
        return queue.size();
    }

    public int getInc() {
        return inc;
    }

    @Override
    public String toString() {
        return "SequenceQueue [queueName=" + queueName + ", queueCapacity=" + queueCapacity + ", inc=" + inc + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((queueName == null) ? 0 : queueName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        SequenceQueue other = (SequenceQueue) obj;
        if (queueName == null) {
            if (other.queueName != null)
                return false;
        } else if (!queueName.equals(other.queueName))
            return false;
        return true;
    }

}
